package com.gydz.gydzbaseframeworkboot.SgsE.controller;

import com.alibaba.fastjson.JSONObject;
import com.gydz.gydzbaseframeworkboot.Common.utils.export.ExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.TableDataInfo;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.domain.TableSelect;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.service.SqlUtilsService;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.BaseCol;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.DeviceToDxc;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.EInterfaceMap;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.YingShe;
import com.gydz.gydzbaseframeworkboot.SgsE.service.EInterfaceMapService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.JingTaiService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.YingSheService;
import com.gydz.gydzbaseframeworkboot.SgsE.util.InterpretResultsUtil;
import com.gydz.gydzbaseframeworkboot.SystemControl.utils.Log;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/EInterfaceMap")
public class EInterfaceMapQueryController {
    private static final Logger log = LoggerFactory.getLogger(EInterfaceMapQueryController.class);

    @Autowired
    YingSheService yingSheService;

    @Autowired
   private EInterfaceMapService eInterfaceMapService;

   @Autowired
   private SqlUtilsService sqlUtilsService;

    @Autowired
    private JingTaiService jingTaiService;

    @ResponseBody
    @Log(remark = "查询E接口下拉框数据")
    @GetMapping("/comtreelist")
    public void comtreelist(HttpServletResponse httpServletResponse) throws IOException {
        HashMap<String,Object> map = new HashMap<String,Object>();
        List<BaseCol> opcOptions = getOptionList("dpc_opc");
//        map.put("baseStationOptions", baseStationOptions);
//        Object jsonObject = JSONObject.toJSON(map);
//        String comtreelist = jsonObject.toString();
        System.out.println("opcOptions:"+opcOptions);
        ResultUtils result =  ResultUtils.succ(200,"查询下拉框数据成功",opcOptions);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    @ResponseBody
    @Log(remark = "查询E接口Map信令记录")
    @PostMapping("/list")
    public void list(HttpServletResponse httpServletResponse, @ModelAttribute("EInterfaceMap") EInterfaceMap eInterfaceMap) throws IOException {
        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7");
        tableSelect.setPrefix("sgs_map_");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        System.out.println("startime==="+eInterfaceMap.getDtsTimeSelect());
        if(eInterfaceMap.getDtsTime() == null){
            ResultUtils result =  ResultUtils.fail("查询E接口Map信令记录失败,请选择查询时间范围");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }else {
            tableSelect.setDateMin(dateFormat.format(eInterfaceMap.getDtsTime()));
        }
        if(eInterfaceMap.getDteTime() == null){
            eInterfaceMap.setDteTime(new Date());
        }
        tableSelect.setDateMax(dateFormat.format(eInterfaceMap.getDteTime()));
        List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
        if(tableList.isEmpty()){
            ResultUtils result =  ResultUtils.fail("没有该时间范围的表");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }


        PageUtils.startPage(new PageParam(eInterfaceMap.getiDisplayStart(),eInterfaceMap.getiDisplayLength(),eInterfaceMap.getsSortDir(),eInterfaceMap.getsSortCol()));
        eInterfaceMap.setTableNameList(tableList);
        List<EInterfaceMap> list = eInterfaceMapService.selectEInterfaceMapList(eInterfaceMap);
        //翻译回填字段
        setNewParamE(list);

        TableDataInfo tableDataInfo = PageUtils.getDataTable(list);

        ResultUtils result =  ResultUtils.succ(200,"查询E接口Map信令成功",tableDataInfo);
        ResultUtils.responseResult(httpServletResponse,result);

    }

    @ResponseBody
@Log(remark = "导出E接口map信令记录")
@RequestMapping("/exportData")
public void exportData(HttpServletRequest request, @ModelAttribute("EInterfaceMap") EInterfaceMap eInterfaceMap, HttpServletResponse response) throws IOException {
        String[] excelHeader = {
                "会话标识","触发时间","主叫IMSI","被叫IMSI","主叫号码",
                "被叫号码","主叫终端","被叫终端","主叫机车号","被叫机车号","OPC","DPC",
                "SLS","主叫GT","被叫GT","主叫SSN","被叫SSN",
                "MAP类型","MTP消息类型","SCCP消息类型","Tcap类型","Tcap_Otid","Tcap_Dtid","Map错误码",
                "源BSC","源小区","目标BSC",
                "目标小区",
                "设备号","端口号","时隙号","链路名称","数据长度","数据内容"};
        String[] ds_titles = {
                "biSessID","dtsTime","vcCallingImsi","vcCalledImsi","vcCallingNumber",
                "vcCalledNumber","vcCallingFN","vcCalledFN","vcCallingTrainID","vcCalledTrainID","intOpc","intDpc",
                "intSLS","vcCallingGT","vcCalledGT","intCallingSSN","intCalledSSN",
                "intOpCode","intMTPType","intSCCPType","intTcapMessageType","intTacpOtid","intTacpDtid","intErrCode",
                "bsc","xiaoQu","bscMu",
                "xiaoQuMu",
                "intCardNo","intCardPort","intCardSlot","intLinkName","intTotalLen","sourceData"};
        int[] widths = {
                256*25, 256*19,256*19, 256*19,256*19,256*19, 256*19,256*19, 256*19,256*19,256*19, 256*19,256*19, 256*19,256*19,
                256*19,256*25, 256*25,256*19, 256*19,256*19, 256*19,256*19, 256*19,256*19,
                256*19,256*30,256*19,256*19,256*30,256*19,256*19,256*30,256*30,
                256*19,256*19, 256*19,256*19,256*19, 256*19};
        int[] ds_format = {
                2,2,2,2,2,2,2,2,2,2,2,2,
                2,2,2,2,2,2,2,2,2,2,
                2,2,2,2,2,2,2,2,2,2,2,2,2,
                2,2,2,2,2};
    TableSelect tableSelect = new TableSelect();
    tableSelect.setTableSchema("ss7"); // 修改为 ss7 表
    tableSelect.setPrefix("sgs_map_"); // 修改为 sgs_map_ 前缀
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    // 使用 eInterfaceMap 的时间范围属性
    if (eInterfaceMap.getDtsTime() == null) {
        ResultUtils result = ResultUtils.fail("查询E接口map信令失败,请选择查询时间范围");
        ResultUtils.responseResult(response, result);
        return;
    } else {
        tableSelect.setDateMin(dateFormat.format(eInterfaceMap.getDtsTime()));
    }

    if (eInterfaceMap.getDteTime() == null) {
        eInterfaceMap.setDteTime(new Date());
    }
    tableSelect.setDateMax(dateFormat.format(eInterfaceMap.getDteTime()));

    List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
    if (tableList.isEmpty()) {
        ResultUtils result = ResultUtils.fail("没有该时间范围的表");
        ResultUtils.responseResult(response, result);
        return;
    }

    eInterfaceMap.setTableNameList(tableList);
    List<EInterfaceMap> list = eInterfaceMapService.selectEInterfaceMapList(eInterfaceMap); // 使用 EInterfaceMap 服务
        //翻译回填字段
        setNewParamE(list);
    try {
        List<Map<String, Object>> data = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int index = 1;
            for (EInterfaceMap rdata : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("index", index);
                map.put("biSessID", rdata.getBiSessID());
                map.put("dtsTime", format.format(rdata.getDtsTime()));
                map.put("vcCallingImsi", rdata.getVcCallingImsi());
                map.put("vcCalledImsi", rdata.getVcCalledImsi());
//                map.put("interfaceID", rdata.getInterfaceID());
                map.put("vcCallingNumber", rdata.getVcCallingNumber());
                map.put("vcCalledNumber", rdata.getVcCalledNumber());
                map.put("vcCallingFN", rdata.getVcCallingFN());
                map.put("vcCalledFN", rdata.getVcCalledFN());
                map.put("vcCallingTrainID", rdata.getVcCallingTrainID());
                map.put("vcCalledTrainID", rdata.getVcCalledTrainID());
                map.put("intOpc", rdata.getIntOpc());
                map.put("intDpc", rdata.getIntDpc());
                map.put("intSLS", rdata.getIntSLS());
                map.put("vcCallingGT", rdata.getVcCallingGT());
                map.put("vcCalledGT", rdata.getVcCalledGT());
                map.put("intCallingSSN", rdata.getIntCallingSSN());
                map.put("intCalledSSN", rdata.getIntCalledSSN());
                map.put("intOpCode", rdata.getIntOpCode());
                map.put("intMTPType", rdata.getIntMTPType());
                map.put("intSCCPType", rdata.getIntSCCPType());
                map.put("intTcapMessageType", rdata.getIntTcapMessageType());
                map.put("intTacpOtid", rdata.getVcTacpOtid());
                map.put("intTacpDtid", rdata.getVcTacpDtid());
                map.put("intErrCode", rdata.getIntErrCode());
                map.put("bsc", rdata.getBsc());
                map.put("xiaoQu", rdata.getXiaoQu());
                map.put("bscMu", rdata.getBscMu());
                map.put("xiaoQuMu", rdata.getXiaoQuMu());
                map.put("intCardNo", rdata.getIntCardNo());
                map.put("intCardPort", rdata.getIntCardPort());
                map.put("intCardSlot", rdata.getIntCardSlot());
                map.put("intLinkName", rdata.getIntLinkName());
                map.put("intTotalLen", rdata.getIntTotalLen());
                map.put("sourceData", rdata.getSourceData());
                index++;
                data.add(map);
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHHmmss");
        ExcelUtil.export("E接口map信令记录数据" + format.format(new Date()), "数据列表", excelHeader, ds_titles, ds_format, widths, data, request, response);
    } catch (Exception e) {
        log.error("导出数据异常", e);
    }
}



   //翻译填充数据
    private List<EInterfaceMap> setNewParamE(List<EInterfaceMap> result){
        String beiJiaoStr;
        String zhuJiaoStr;
        String BSCLacMu;
        String BSCLac;
        String lac;
        String ci;
        String lacMu;
        String ciMu;
        List<DeviceToDxc> deviceToDxcList=jingTaiService.queryDeviceToDxc();
        for (EInterfaceMap middleE: result) {
            if (deviceToDxcList.size()>0) {

                for (int i = 0; i < deviceToDxcList.size(); i++) {
                    if (middleE.getIntCardNo().equals(deviceToDxcList.get(i).getIntCardNo()) && middleE.getIntCardPort().equals(deviceToDxcList.get(i).getIntCardPort()) && middleE.getIntCardSlot().equals(deviceToDxcList.get(i).getIntCardSlot())) {
                        middleE.setIntDxcId(deviceToDxcList.get(i).getIntDXCId());
                        middleE.setIntDxcPort(deviceToDxcList.get(i).getIntDXCPort());
                        middleE.setIntDxcTs(deviceToDxcList.get(i).getIntDXCTs());
                        middleE.setIntLinkName(deviceToDxcList.get(i).getIntLinkName());
                        System.out.println(middleE.getIntLinkName());
                    }
                }
            }

            beiJiaoStr = middleE.getVcCalledFN();

            if(beiJiaoStr.length()>6){
                middleE.setVcCalledFN(InterpretResultsUtil.getChangHaoMa(beiJiaoStr,yingSheService));
            }else if(beiJiaoStr.length()>2){
                middleE.setVcCalledFN(yingSheService.getMap("duanHaoMaMap").get(beiJiaoStr));
            }else if(middleE.getVcCalledNumber().length()>2){
                middleE.setVcCalledFN(yingSheService.getMap("zhongDuanMap").get(middleE.getVcCalledNumber().substring(3)));
            }else if(middleE.getVcCalledImsi().length()>3&&middleE.getVcCalledImsi().length()>12){
                middleE.setVcCalledFN(yingSheService.getMap("zhongDuanMap").get(middleE.getVcCalledImsi().substring(5,13)));
            }
            zhuJiaoStr = middleE.getVcCallingFN();
            if(zhuJiaoStr.length()>6){
                middleE.setVcCallingFN(InterpretResultsUtil.getChangHaoMa(zhuJiaoStr,yingSheService));
            }else if(zhuJiaoStr.length()>2){
                middleE.setVcCallingFN(yingSheService.getMap("duanHaoMaMap").get(zhuJiaoStr));
            }else if(middleE.getVcCallingNumber().length()>2){
                middleE.setVcCallingFN(yingSheService.getMap("zhongDuanMap").get(middleE.getVcCallingNumber().substring(3)));
            }else if(middleE.getVcCallingImsi().length()>3&&middleE.getVcCallingImsi().length()>12){
                middleE.setVcCallingFN(yingSheService.getMap("zhongDuanMap").get(middleE.getVcCallingImsi().substring(5,13)));
            }

//            middleE.setInterfaceID(InterpretResultsUtil.getCodingMap("InterfaceId",middleE.getInterfaceID()));
            middleE.setIntOpc(yingSheService.getMap("dpcOpcMap").get(middleE.getIntOpc()));
            middleE.setIntDpc(yingSheService.getMap("dpcOpcMap").get(middleE.getIntDpc()));
            middleE.setIntCallingSSN(InterpretResultsUtil.getCodingMap("SCCPSubsystem",middleE.getIntCallingSSN()));
            middleE.setIntCalledSSN(InterpretResultsUtil.getCodingMap("SCCPSubsystem",middleE.getIntCalledSSN()));
            middleE.setIntSCCPType(InterpretResultsUtil.getCodingMap("sCCPP",middleE.getIntSCCPType()));
            middleE.setIntTcapMessageType(InterpretResultsUtil.getCodingMap("tCAP",middleE.getIntTcapMessageType()));
            middleE.setIntErrCode(InterpretResultsUtil.getCodingMap("MapNewError",middleE.getIntErrCode()));
            middleE.setIntOpCode(InterpretResultsUtil.getCodingMap("Map",middleE.getIntOpCode()));
            middleE.setIntMTPType(middleE.getIntMTPType().equals("3")?"SCCP":"其他");
            middleE.setSourceData(InterpretResultsUtil.getSData(middleE.getSourceData()));
            middleE.setNewSourceData(middleE.getSourceData());
            BSCLacMu = yingSheService.getMap("BSCLacMap").get(middleE.getUintTCgiLac()+"-"+middleE.getUintTCgiCi());
            if(BSCLacMu!=null&&!BSCLacMu.isEmpty()){
                middleE.setBscMu(BSCLacMu.substring(0,BSCLacMu.indexOf("-")));
                middleE.setXiaoQuMu(BSCLacMu.substring(BSCLacMu.indexOf("-")+1));
            }
            BSCLac = yingSheService.getMap("BSCLacMap").get(middleE.getUintSCgiLac()+"-"+middleE.getUintSCgiCi());
            if(BSCLac!=null&&!BSCLac.isEmpty()){
                middleE.setBsc(BSCLac.substring(0,BSCLac.indexOf("-")));
                middleE.setXiaoQu(BSCLac.substring(BSCLac.indexOf("-")+1));
            }
            lac = middleE.getUintSCgiLac();
            ci = middleE.getUintSCgiCi();
            lacMu = middleE.getUintTCgiLac();
            ciMu = middleE.getUintTCgiCi();
            if(lac!=null&&!lac.isEmpty()&&ci!=null&&!ci.isEmpty()){
                middleE.setUintSCgiLac(lac.equals("0")?"":lac);
                middleE.setUintSCgiCi(ci.equals("0")?"":ci);
                middleE.setUintTCgiLac(lacMu.equals("0")?"":lacMu);
                middleE.setUintTCgiCi(ciMu.equals("0")?"":ciMu);
                lac = middleE.getUintSCgiLac();
                ci = middleE.getUintSCgiCi();
                lacMu = middleE.getUintTCgiLac();
                ciMu = middleE.getUintTCgiCi();
                if(!lac.isEmpty()&&!ci.isEmpty()){
                    middleE.setCgi("460-20-"+lac+"-"+ci);
                }
                if(!lacMu.isEmpty()&&!ciMu.isEmpty()){
                    middleE.setCgiMu("460-20-"+lacMu+"-"+ciMu);
                }
            }
        }
        return result;
    }

    List<BaseCol> getOptionList(String optionName){
//        HashMap<String,Object> map = new HashMap<String,Object>();
//        map.put("colName", optionName);
        List<YingShe> sectionNames = yingSheService.getYingShecomtreeList(optionName);
        List<BaseCol> sectionNameOptions = new ArrayList<BaseCol>();
        if(sectionNames != null && sectionNames.size() > 0){
            for(YingShe value : sectionNames){
                if(StringUtils.isNotBlank(value.getValue())){
                    value.setValue(value.getValue().replaceAll("\\s*|\r|\n|\t|\'|\"",""));
                    sectionNameOptions.add(new BaseCol(value.getName(),value.getValue()));
                }
            }
        }
        return sectionNameOptions;
    }





}
